package org.sourcecode.common.cas.client;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

public abstract class SignInFilter extends AbstractSignFilter {

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		signin(request, response);
		chain.doFilter(request, response);
	}

	protected void signin(HttpServletRequest request, HttpServletResponse response) {
		String ticketName = SignCheckFilter.TICKET;
		String cookie_ticket = CasSessionUtils.getCookie(request, ticketName);

		String session_ticket = (String) request.getSession().getAttribute(SignCheckFilter.SESSION_TICKET_NAME);

		if (StringUtils.hasText(cookie_ticket) == false) {
			cookie_ticket = request.getParameter(ticketName);
		}
		if (!StringUtils.hasText(cookie_ticket) || session_ticket != null) {
			return;
		}
		try {
			boolean suc = addSession(request, cookie_ticket);
			if (suc)
				request.getSession().setAttribute(SignCheckFilter.SESSION_TICKET_NAME, cookie_ticket);
		} catch (Exception e) {
			log.warn("add session fail: " + ticketName, e);
		}

	}

	protected abstract boolean addSession(HttpServletRequest request, String ticket) throws Exception;

}
